from sqlalchemy import or_

from easyRead.api import bp
from easyRead.extensions import db
from easyRead.api.errors import bad_request, error_response
from flask import request, jsonify, url_for, g, current_app, make_response
from easyRead.models import User


@bp.route('/users/', methods=['GET'])  # 搜索查询，若没有则显示全部
def get_users():
    search = request.args.get('search')
    users_output = []
    if search is None:
        users = User.query.all()
    else:
        users = User.query.filter(or_(User.nickname.like(f"%{search}%"), User.id == search)).all()
    for user in users:
        users_output.append(user.to_json())
    return jsonify(users_output)


@bp.route('/users/<level>', methods=['GET'])  # 按权限查询用户 student:学生 teacher:老师 admin:普通管理员
def get_users_by_level(level):
    users = User.query.filter(User.level == level).all()
    users_output = []
    for user in users:
        users_output.append(user.to_json())
    return jsonify(users_output)


@bp.route('/users/<id>', methods=['PUT'])  # 修改一个用户,目前只能修改学生邮箱/手机号/权限
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json()
    if not data:
        return bad_request('You must post JSON data.')

    if 'email' in data:
        user.email = data['email']

    if 'phone' in data:
        user.phone = data['phone']

    if 'level' in data:
        user.level = data['level']

    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()

    return jsonify()


@bp.route('/users/', methods=['POST'])  # 新增用户
def add_user():
    user_dict = request.get_json()
    id = user_dict.get('id')
    password = user_dict.get('password')
    nickname = user_dict.get('nickname')
    email = user_dict.get('email')
    phone = user_dict.get('phone')
    level = user_dict.get('level')

    user = User(id, password, nickname, email, phone, level)
    db.session.add(user)
    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()

    return jsonify()
